package cn.king.springframework.beans.factory;

import cn.king.springframework.beans.BeanException;
import cn.king.springframework.beans.PropertyValue;
import cn.king.springframework.beans.PropertyValues;
import cn.king.springframework.beans.factory.config.BeanFactoryPostProcessor;
import cn.king.springframework.core.io.DefaultResourceLoader;
import cn.king.springframework.core.io.Resource;

import java.io.IOException;
import java.util.Properties;

public class PropertyPlaceholderConfigurer implements BeanFactoryPostProcessor {
    /**
     * Default placeholder prefix: {@value}
     */
    public static final String DEFAULT_PLACEHOLDER_PREFIX = "${";
    /**
     * Default placeholder suffix: {@value}
     */
    public static final String DEFAULT_PLACEHOLDER_SUFFIX = "}";
    private String location;
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeanException {
        // 加载属性文件
        try {
            DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
            Resource resource = resourceLoader.getResource(location);
            Properties properties = new Properties();
            properties.load(resource.getInputStream());
            String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
            for(String beanName:beanDefinitionNames){
                PropertyValues propertyValues = beanFactory.getBeanDefinition(beanName).getPropertyValues();
                for(PropertyValue propertyValue:propertyValues.getPropertyValues()){
                    Object value = propertyValue.getValue();
                    if(!(value instanceof String)){
                        continue;
                    }
                    String strVal = (String) value;
                    StringBuilder buffer = new StringBuilder(strVal);
                    int startIndex = strVal.indexOf(DEFAULT_PLACEHOLDER_PREFIX);
                    int stopIndex = strVal.indexOf(DEFAULT_PLACEHOLDER_SUFFIX);
                    if(startIndex != -1 && stopIndex != -1 && startIndex < stopIndex){
                        String propKey = strVal.substring(startIndex + 2, stopIndex);
                        String propVal = properties.getProperty(propKey);
                        buffer.replace(startIndex,stopIndex+1,propVal);
                        propertyValues.addPropertyValue(new PropertyValue(propertyValue.getName(),buffer.toString()));
                    }

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void setLocation(String location) {
        this.location = location;
    }
}
